package com.liu.manag.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FileUtil {

    /**
     * 写入文件
     *
     * @param target
     * @param src
     * @throws IOException
     */
    public static void write(String target, InputStream src) throws IOException {
        OutputStream os = new FileOutputStream(target);
        byte[] buf = new byte[1024];
        int len;

        while ((len = src.read(buf)) != -1) {
            os.write(buf, 0, len);
        }

        os.flush();
        os.close();
    }


    /**
     * 分块写入文件s
     */
    public static void writeWithBlock(String target,Long targetSize,InputStream src,Long srcSize,Integer chunks,Integer chunk) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(target,"rw");

        randomAccessFile.setLength(targetSize);

        if(chunk == (chunks - 1) && chunk != 0){
            randomAccessFile.seek(chunk * (targetSize - srcSize) / chunk);
        }else{
            randomAccessFile.seek(chunk * srcSize);
        }

        byte[] buf = new byte[1024];
        int len;
        while((len = src.read(buf)) != -1){
            randomAccessFile.write(buf,0,len);
        }
        randomAccessFile.close();


    }

    public static String generateFileName(){
        return UUID.randomUUID().toString();
    }

    public static String getFileSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }
    public static String getUUIDFileName(MultipartFile file){
        return generateFileName()+getFileSuffix(file.getOriginalFilename());
    }
    public static void beforeCreateDirs(String target) {
        File fileCreate = new File(target);
        if (!fileCreate.exists()) {
            fileCreate.mkdirs();
        }
    }
}
